package com.example.personblog.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class MD5Util {
    
    private static final String SALT_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int SALT_LENGTH = 16;
    
    /**
     * 生成随机盐值
     */
    public static String generateSalt() {
        StringBuilder salt = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < SALT_LENGTH; i++) {
            salt.append(SALT_CHARS.charAt(random.nextInt(SALT_CHARS.length())));
        }
        return salt.toString();
    }
    
    /**
     * MD5加密（带盐）
     */
    public static String encrypt(String password, String salt) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 加入盐值
            String inputStr = password + salt;
            md.update(inputStr.getBytes());
            byte[] result = md.digest();
            
            // 将byte数组转换为16进制字符串
            StringBuffer sb = new StringBuffer();
            for (byte b : result) {
                String hex = Integer.toHexString(b & 0xFF);  //加盐  （任何数与0xff进行与运算都是取十六进制后两位）
                if (hex.length() == 1) {
                    sb.append("0");
                }
                sb.append(hex);
            }
            return sb.toString();  //返回标准MD5加密后结果
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5加密失败", e);
        }
    }
    
    /**
     * 验证密码
     */
    public static boolean verify(String password, String salt, String md5) {
        return encrypt(password, salt).equals(md5);
    }
} 